package dao

import (
	"context"
	"database/sql"
	"git.supremind.info/product/box/vehicle/internal/util"
	"log"
	"time"
)

type VehicleModelChemical struct {
	ID                uint     `gorm:"primary_key" json:"id"`
	EventId           uint32   `json:"event_id"`
	HazardousChemical string   `json:"hazardous_chemical"`
	CreateTime        BaseTime `json:"create_time"`
}

type DTO struct {
	DBFile string
	db     *sql.DB
}

var dto = &DTO{}

func (ac *VehicleModelChemical) TableName() string {
	return "vehicle_model_chemical"
}

func (ac *VehicleModelChemical) Insert() (uint, error) {
	if err := DB.Create(ac).Error; err != nil {
		util.Log().Error("无法插入数据库记录, %s", err)
		return 0, err
	}
	return ac.ID, nil
}

func Init(DBFile string) *DTO {
	db, err := sql.Open("sqlite3", DBFile)
	if err != nil {
		log.Fatalf("open config db failed, err: %v", err)
	}
	sqlStmt := `
	CREATE TABLE IF NOT EXISTS vehicle_model_chemical (
		id 			INTEGER PRIMARY KEY AUTOINCREMENT,
		event_id	INTEGER NOT NULL,
		hazardous_chemical 	TEXT NOT NULL,
		create_time	DATETIME NOT NULL
	);`
	_, err = db.Exec(sqlStmt)
	if err != nil {
		log.Fatalf("%q: %s", err, sqlStmt)
	}
	return &DTO{
		DBFile: DBFile,
		db:     db,
	}
}

func (c DTO) Set(ctx context.Context) error {
	stmt, err := c.db.PrepareContext(ctx, `INSERT INTO vehicle_model_chemical(event_id, hazardous_chemical, create_time) VALUES(?, ?, ?)`)
	if err != nil {
		//log.Warnf("prepare err: %v", err)
		return err
	}
	defer stmt.Close()
	//infoStr := util.JsonStr(info)
	_, err = stmt.ExecContext(ctx, 12, "危化品", time.Now())
	if err != nil {
		//log.Warnf("exec err: %v", err)
		return err
	}
	return nil
}

func (c DTO) Get(ctx context.Context) (configs []VehicleModelChemical, err error) {
	stmt, err := c.db.PrepareContext(ctx, `SELECT * FROM vehicle_model_chemical`)
	if err != nil {
		//log.Warnf("prepare query err: %v", err)
		return nil, err
	}

	defer stmt.Close()

	rows, err := stmt.QueryContext(ctx)
	if err != nil {
		//log.Warnf("query err: %+v", err)
		return nil, err
	}
	for rows.Next() {
		var model VehicleModelChemical
		err = rows.Scan(
			&model.ID,
			&model.EventId,
			&model.HazardousChemical,
			&model.CreateTime,
		)
		if err != nil {
			//log.Warnf("scan err: %v", err)
			continue
		}
		configs = append(configs, model)
	}

	return configs, nil
}
